import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js'
import doT from '../../../../vendor/template/doT.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import watermark from '../../../common/watermark.js';
import { Collaboration_APP, TEST_NUMBER, YY_NUMBER } from '../../../../../public/js/config/config.js';
import { requestDict, DictionaryType } from '../../../common/dictionary/dictionary-type.js';

(function (window, document, $) {
    let _speLevelList, listindex = "";
    // 获取参数
    const _json = Utils.ParsingUrl(window.location);
    const looksalesTemplate = doT.template($('#looksalesplan-template').text());
    const lksalesmainTemplate = doT.template($('#looksalesplanmain-template').text());
    const saleMainTemplate = doT.template($('#saleMain-template').text());
    const saleEntryTemplate = doT.template($('#saleEntry-template').text());

    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
         _watermarkBgImg();
    });

    // //销售品类
    requestDict(DictionaryType.LEVEL_TYPE).then(res => {
        _speLevelList = res.data;
        _initCommand()
    });

    //返回列表
    $(document).on('click', '#returnlist', function () {
        location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()}`;
    });

    //切换导航栏
    $('#spleplan-navbar a').on('click', function () {
        listindex = Number($(this).index());
        $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
        if (listindex === 0) { //销售出库
            listindex = ""
            _initCommand()
        } else { //销售订单
            _initSaleOrder();
        }
    });

    //命令初始化
    const _initCommand = async () => {
        if (Utils.IsNotNull(_json.orderId)) {
            $('#spleplan-navbar').css('display', '')
        } else {
            $('#spleplan-navbar').css('display', 'none')
        }
        let ids = getUrlKey("id")
        DeliverApi.getDeliverinfo(ids).then(res => {
            let bizFormObj = {
                bizDate: res.bizFormObj.bizDate,
                billNo: res.bizFormObj.billNo,
                billStatus: res.bizFormObj.billStatus,
                remark: res.remark,
                saleOrgName: res.saleOrg.name
            }
            res.entries = res.entries.map(item => {
                let specLevel = '';
                if (Utils.IsNotNull(_speLevelList.find(s => s.value == item.specLevel))) {
                    specLevel = _speLevelList.find(s => s.value == item.specLevel).displayName;
                } else {
                    specLevel = item.specLevel;
                }
                return { ...item, specLevel }
            });
            $('#looksalesMain').empty().append(lksalesmainTemplate(bizFormObj));
            $('#looksalesEntry').empty().append(looksalesTemplate({ entreis: res.entries }));
            res.entries.map((item, index) => {
                if (Utils.IsNotNull(item.attaches)) {
                    _viewImages(item.attaches, `uploaderFiles${index}`);
                }
            });
        });
    }

    //查询销售订单信息
    const _initSaleOrder = () => {
        DeliverApi.getDetailsSaleOrder(_json.orderId).then(res => {
            let entry = {
                billStatus: res.billStatus,
                bizDate: res.bizDate,
                cstmName: res.cstmName,
                cstmNumCode: res.cstmNumCode,
                salePerName: res.salePerName,
                salePerNumCode: res.salePerNumCode
            }
            res.entreis = res.entreis.map(item => {
                let specLevel = '';
                let receiveAddress = "";
                let detailDeliveryAddress = "";
                if (Utils.IsNotNull(item.shipRegion)) {
                    let areaId = item.shipRegion.split('|');
                    let split = areaId[1].split(';');
                    receiveAddress = split[0] + split[1] + split[2] + split[3] + item.shipAddress
                } else {
                    receiveAddress = item.shipAddress;
                }
                if (Utils.IsNotNull(item.deliveryRegion)) {
                    let areaId = item.deliveryRegion.split('|');
                    let split = areaId[1].split(';');
                    detailDeliveryAddress = split[0] + split[1] + split[2] + split[3] + item.deliveryAddress
                } else {
                    detailDeliveryAddress = item.deliveryAddress;
                }
                if (Utils.IsNotNull(_speLevelList.find(s => s.value == item.specLevel))) {
                    specLevel = _speLevelList.find(s => s.value == item.specLevel).displayName;
                } else {
                    specLevel = item.specLevel;
                }
                return { ...item, specLevel, receiveAddress, detailDeliveryAddress }
            });
            $('#looksalesMain').empty().append(saleMainTemplate(res));
            $('#looksalesEntry').empty().append(saleEntryTemplate({ entreis: res.entreis, entry: entry }));
            if (Utils.IsNotNull(res.attaches)) {
                _viewImages(res.attaches, "uploaderFiles");
            }
        });
    }

    /** 获取地址栏的 参数  传入 字段返回值 */
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    // //附件回显
    const _viewImages = async (images, id) => {
        let _imag = images.split(',');
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    if (_res.isSucceed) {
                        let _li;
                        if (["jpg", "jpeg", "png", 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;

                        }
                        $(`#${id}`).append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
        }
        $(document).on('click', `#${id}`, function (e) {
            let target = e.target;
            while (!target.classList.contains(`weui-uploader__file`) && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
            });
            $('.weui-icon_gallery-delete').css('display', 'none')
        });
    }

    // //添加水印信息
     const _watermarkBgImg = () => {
         let _userInfo = JSON.parse(Utils.GetSessionStorage("SNAccountEply")) || {};
         watermark.set(_userInfo.name + _userInfo.numCode);// 水印
         //DeliverApi.queryUserName(Utils.GetQueryString('state') || YY_NUMBER.sourceID).then(res => {
         //    watermark.set(_userInfo.un + res.code);// 水印
         //}).catch(_ => {
         //    watermark.set(_userInfo.un);// 水印
         //});
     }

})(window, document, jQuery)